package com.sqx.modules.search.factory;

import com.sqx.modules.search.factory.strategy.SearchStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description：TODO 1动态搜索 2活动搜索 3用户搜索 4商品搜索 5店铺搜索
 * @author： qiao
 * @create： 2024/5/8 10:51
 */
@Component
public class SearchFactory {

    public  final Map<Integer, SearchStrategy> searchFunctionMap;

    @Autowired(required = false)
    public SearchFactory(List<SearchStrategy> strategyList) {
        this.searchFunctionMap=new HashMap<>();
        for (SearchStrategy strategy : strategyList) {
            try {
                Field identifylabel = strategy.getClass().getDeclaredField("SEARCHID");
                if (identifylabel != null && int.class.equals(identifylabel.getType())){
                    identifylabel.setAccessible(true);
                    int identifierInt = identifylabel.getInt(null);
                    //map中存储的为key 为 1 vlaue 为strategy
                    searchFunctionMap.put(identifierInt,strategy);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public SearchStrategy getFunction(Integer key){
        SearchStrategy strategy = searchFunctionMap.get(key);
        return strategy;
    }
}
